from random import randint

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from libs.ronglianyun.sms import send_message


class  ImagecodeView(View):

    #http://www.meiduo.site:8000/image_codes/bcd9a401-637c-4474-807f-7eec01cd418b/
    def get(self,request,uuid):
        text,image = captcha.generate_captcha()
        redis_cli = get_redis_connection('code')
        redis_cli.setex(uuid,100,text)
        return HttpResponse(image,content_type='image/png')

class SmscodeView(View):

    def get(self,request,mobile):

        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not  all([image_code,uuid]):
            return JsonResponse({'coede':400,'errmsg':'参数不全'})

        redis_cli = get_redis_connection('code')
        redis_image_code= redis_cli.get(uuid)

        if redis_image_code is None:
            return JsonResponse({'coede':400,'errmsg':'图片验证码过期'})
        if redis_image_code.decode().lower() != image_code.lower():
            return  JsonResponse({'coede':400,'errmsg':'图片验证码错误'})
        sms_code = '%06d'%randint(0,999999)
        # 保存验证码redis
        redis_cli.setex(mobile,300,sms_code)
        # 发送短信验证码
        send_message('1',mobile,(sms_code,'5'))

        return JsonResponse({'coede':0,'errmsg':'ok'})